package com.ddc.drivers.fmpxml;

import java.sql.*;
import java.util.Properties;
import java.net.MalformedURLException;

public class Driver implements java.sql.Driver {
	static {
		try {
			DriverManager.registerDriver( new Driver() );
		} catch( SQLException e ) {
			throw new RuntimeException( e );
		}
	}

	/** Creates a new {@link FmConnection} by passing the parameters into the constructor of the Connection. */
	public Connection connect( String url, Properties properties ) throws SQLException {
        try {
        	   //Primary Key & Layout Filters
        		String pk = getParams(url, "pk");
        		if(pk==null)
        			pk = "id";
        		String layFilter = getParams(url, "layFilter");
        		
        		//parse URL
        		int myPos = url.indexOf(";");
        		if(myPos > 0){
        			url = url.substring(0, myPos);
        		}
            
            return new FmConnection(url, properties, pk, layFilter);
        } catch( MalformedURLException e ) {
            SQLException sqlException = new SQLException( url + " is not a valid JDBC URL (" + e.getMessage() + "). URL's should be in the format: jdbc:ddc://hostname:portnumber/databasename?property1=value1&property2=value2" );
            sqlException.initCause(e);
            throw sqlException;
        }
	}
	
	//splits up URL to get parameters
	private String getParams(String in, String paramName){
		int paramLength = paramName.length()+1;
		int pos = in.indexOf(paramName + "=");
		//if it exist in the string
		if(pos>0){
			//check to see if there are more params after it
			int nextParam = in.indexOf(";", pos+1);
			if(nextParam>0){
				return in.substring(pos+paramLength, nextParam);
			}
			else{
				return in.substring(pos+paramLength);
			}
		}
		else{
			return null;
		}
	}

	/** Returns true if the word 'fmp360' appears in the URL. */
	public boolean acceptsURL( String s ) throws SQLException {
		return ( s != null && s.indexOf("fmp360") > -1 );
	}

	/** Alwasy returns an empty array. This method is unnecessary for basic operation; it is an optional
	 * method to allow a GUI to prompt a user for more required connection parameters. */
	public DriverPropertyInfo[] getPropertyInfo( String s, Properties properties ) throws SQLException {
		return new DriverPropertyInfo[0];
	}

	public int getMajorVersion() {
		return 1;
	}

	public int getMinorVersion() {
		return 0;
	}

	/** Returns false, since there are many aspects of standard ANSI SQL that we will not be supporting. */
	public boolean jdbcCompliant() {
		return false;
	}
}